#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#include "getopt.h"
#include "bb_api.h"
#include "prj_rpc.h"

static bb_dev_handle_t *bb_handle;

int main(int argc, char ** argv)
{
	int s32Ret;
    int dev_num = 0;
    uint8_t mode;
    bb_host_t* phost=NULL;
    bb_dev_t** devs=NULL;
	bb_set_prj_dispatch_in_t set_prj = {0};
    bb_get_prj_dispatch_in_t get_prj_in;
    bb_get_prj_dispatch_out_t get_prj_out;
	prj_rpc_hdr_t *hdr;
    prj_cmd_set_work_mode_t set_work_mode = {0};
    prj_cmd_get_work_mode_t *get_work_mode;
    bb_set_reboot_t reboot;

    if(argc == 1){
		return -1;
	}

    while((s32Ret = getopt(argc, argv, "m:")) != -1)
    {
        switch(s32Ret)
		{
            case 'm':
                mode = atoi(optarg);
                printf("mode %d\n", mode);
                break;
            default:
                printf("unknow cmd param !\n");
                return -1;
        }
    }

	s32Ret = bb_host_connect(&phost,"127.0.0.1",BB_PORT_DEFAULT);
	if(s32Ret)
	{
		printf("bb connect error,ret=%d\n",s32Ret);
		return -1;
	}

    printf("bb_host_connect ret %d\n", s32Ret);

    dev_num = bb_dev_getlist(phost,&devs);

    bb_handle = bb_dev_open(devs[0]);

    if (!bb_handle) {
		printf("bb_dev_open error\n");
		return -1;
    }

    bb_dev_freelist(devs);

    /* set work mode */
    set_work_mode.work_mode = mode;
    hdr=(prj_rpc_hdr_t *)set_prj.data;
    hdr->cmdid = PRJ_CMD_SET_WORK_MODE;
    memcpy(hdr->data, &set_work_mode, sizeof(prj_cmd_set_work_mode_t));
    bb_ioctl(bb_handle, BB_SET_PRJ_DISPATCH, &set_prj, NULL);

    /* check work mode */
    mode = 0;
    hdr=(prj_rpc_hdr_t *)get_prj_in.data;
    hdr->cmdid = PRJ_CMD_GET_WORK_MODE;
    bb_ioctl(bb_handle, BB_GET_PRJ_DISPATCH, &get_prj_in, &get_prj_out);
    hdr = (prj_rpc_hdr_t *)get_prj_out.data;
    get_work_mode = (prj_cmd_get_work_mode_t *)hdr->data;
    printf("get workmode %d\n", get_work_mode->work_mode);

    /* reboot 8030 */
    printf("cfg end, reboot!\n");
    reboot.tim_ms = 0;
    bb_ioctl(bb_handle, BB_SET_SYS_REBOOT, &reboot, NULL);

    printf("test end, exit!\n");

    exit(0);
}
